package com.itheima.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional
public class DishServiceImpl implements DishService {
    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询有多小记录数
     *
     * @param categoryId
     * @return
     */
    @Override
    public int selectByCategoryId(Long categoryId) {
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();

        lqw.eq(Dish::getCategoryId, categoryId);

        return dishMapper.selectCount(lqw);

    }

    @Override
    public void saveWithFlavor(DishDto dishDto) {
        String key="dish_"+dishDto.getCategoryId()+"_1";

        //这个没有问题的，一个传入的是一个包装类对象，一个是传入一个实体对象
        //保存菜品的基本信息到dish表中
        dishMapper.insert(dishDto);
        Long dishId = dishDto.getId();//菜品id
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().map((item) -> {
            //设置口味属于那个菜品
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveWithFlavor(flavors);
        redisTemplate.delete(key);

    }

    @Override
    public Page findPage(int page, int pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageDish = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //构造条件
        lqw.like(name != null, Dish::getName, name);
        //添加排序条件
        lqw.orderByAsc(Dish::getUpdateTime);
        //执行分页查询
        dishMapper.selectPage(pageDish, lqw);

        //对象拷贝
        BeanUtils.copyProperties(pageDish, dishDtoPage, "records");
        List<Dish> records = pageDish.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long id = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryMapper.selectById(id);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //设置菜品的口味。
            dishDto.setFlavors(dishFlavorService.findByDishId(item.getId()));
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return dishDtoPage;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //修改的话，清空原来分类的缓存，和现在修改成分类的缓存
        String key="dish_"+dishDto.getCategoryId()+"_1";
        Dish oldDish = dishMapper.selectById(dishDto.getId());
        long cateOld = oldDish.getCategoryId();
        long newcateID = dishDto.getCategoryId();
          if (cateOld==newcateID){
              redisTemplate.delete(key);
          }else{
              redisTemplate.delete("dish_"+cateOld+"_1");
              redisTemplate.delete("dish_"+newcateID+"_1");
          }

        //更新dish表的基本信息
        dishMapper.updateById(dishDto);
        //清理当前菜品对应的口味数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorMapper.delete(lqw);
        //添加当前提交过来的数据,
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveWithFlavor(flavors);
    }

    /**
     * 根据菜品分类 category_id 和sates=1 查询dish 菜品
     *
     * @param dish
     * @return
     */
    @Override
    public List<DishDto> list(Dish dish) {
        List<DishDto> dishDtoList=null;
        //动态构造Key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
       //存的就是String 取得就是String 再转
        String data = (String) redisTemplate.opsForValue().get(key);
        if (data!=null){
            return JSON.parseObject(data,List.class);
        }
        //创建条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        lqw.eq(Dish::getStatus, 1);
        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询条件
        List<Dish> list = dishMapper.selectList(lqw);
        //List<DishDto>
        dishDtoList = list.stream().map((item) -> {
            //每次循环都创建一个DisDto对象
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查分类对象
            Category category = categoryMapper.selectById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> dlqw = new LambdaQueryWrapper<>();
            dlqw.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(dlqw);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        //如果缓存中没有数据，，需要查询数据库，将查询到的菜品数据缓冲到Redis
        redisTemplate.opsForValue().set(key,JSON.toJSONString(dishDtoList),60, TimeUnit.MINUTES);
        return dishDtoList;
    }

    /**
     * 根据菜品id 删除菜品
     * 这里有菜品表和口味表
     *
     * @param ids
     */
    @Override
    public int deleteDish(List<Long> ids) {
        //dishMapper.deleteBatchIds(ids);
        //1.0菜品在起售状态下是不能删除的
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId, ids);
        lqw.eq(Dish::getStatus, 1);
        Integer count = dishMapper.selectCount(lqw);
        if (count > 0) {
            throw new CustomException("菜品正在出售，请停售再删除");
        }
        //2.0如果能删除就先删除菜品表，再根据菜品id删除口味表
        //2.1先删除菜品
        int row = dishMapper.deleteBatchIds(ids);
        //2.2删除口味表
        LambdaQueryWrapper<DishFlavor> qlqw = new LambdaQueryWrapper<>();
        qlqw.in(DishFlavor::getDishId, ids);
        dishFlavorMapper.delete(qlqw);
        return row > 0 ? 1 : 0;
    }

    /**
     * 根据id 和状态修改 菜品状态
     * @param ids
     * @param status
     * @return
     */
    @Override
    public int updateDishStatus(List<Long> ids, Integer status) {

        int row = 0;
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            dish.setStatus(status);

            row += dishMapper.updateById(dish);
        }
        /*lqw.in(Dish::getId,ids);
        lqw.eq(Dish::getStatus,status);
        int rows = dishMapper.u;*/
        return row;
    }
}
